package com.mini.demos.webgame.codec;

import java.util.logging.Logger;

import org.apache.mina.core.buffer.IoBuffer;

import com.mini.demos.webgame.msg.AbstractGameMsg;
import com.mini.demos.webgame.msg.MsgHead;
import com.mini.demos.webgame.util.Constants;
import com.mini.framework.communicate.mina.protocol.DecodeResult;
import com.mini.framework.communicate.mina.protocol.Decoder;
import com.mini.framework.communicate.mina.protocol.Msg;

public abstract class AbstractDecoder implements Decoder {
	
	private Logger log = Logger.getLogger("abstractDecoder.");

	public DecodeResult decodeAble(IoBuffer byteBuffer) {
		log.info("msg:" +byteBuffer.getHexDump());
		int remain = byteBuffer.remaining();
		if(remain < Constants.HEAD_LEN){
			return DecodeResult.NEED_DATA;
		}else{
			int version = byteBuffer.getInt();
			int commandId = byteBuffer.getInt();
			if(!isLegalCommand(commandId)){
				return DecodeResult.NOT_OK;
			}
		}
		
		return DecodeResult.OK;
	}
	
	public Msg decode(IoBuffer byteBuffer) {
		MsgHead head = decodeHead(byteBuffer);
		AbstractGameMsg msg = decodeBody(byteBuffer,head);
		return msg;
	}
	
	public MsgHead decodeHead(IoBuffer buffer){
		MsgHead head = new MsgHead();
		head.setVersion(buffer.getInt());
		head.setCommandId(buffer.getInt());
		head.setSeqId(buffer.getInt());
		head.setTotalLength(buffer.getInt());
		head.setTime(buffer.getInt());
		head.setSpace(buffer.getInt());
		return head;
	}
	
	public abstract boolean isLegalCommand(int commandId);
	
	public abstract AbstractGameMsg decodeBody(IoBuffer buffer,MsgHead head);

}
